package parser;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import javax.naming.OperationNotSupportedException;

public class Record implements Iterable<Line> {

	private Map<Tag, Field> fields = new TreeMap<Tag, Field>();

	String rawData;

	String id; // ?

	public Map<Tag, Field> getFieldMap() {
		return Collections.unmodifiableMap(fields);
	}

	public Collection<Field> getFields() {
		return fields.values();
	}

	public Field getField(Tag tag) {
		return fields.get(tag);
	}

	void add(Tag tag, Field field) {
		fields.put(tag, field);
	}

	void add(Field field) {
		if (field == null)
			throw new IllegalArgumentException();
		Tag tag = field.tag;
		fields.put(tag, field);
	}

	void add(Line line) throws OperationNotSupportedException {
		if (line == null)
			throw new IllegalArgumentException();
		Tag tag = line.tag;
		Field field = fields.get(tag);
		if (field == null) {
			field = new Field(line);
			fields.put(tag, field);
		} else
			field.add(line);
	}

	public String getRawData() {
		return rawData;
	}

	public String getId() {
		return id;
	}

	

	class MyIterator implements Iterator<Line> {

		public MyIterator() {
			fieldsIterator = getFields().iterator();
			if (fieldsIterator.hasNext())
				lineIterator = fieldsIterator.next().iterator();
		}

		Iterator<Line> lineIterator;

		Iterator<Field> fieldsIterator;

		@Override
		public boolean hasNext() {
			/*
			 * Felder sind per definitionem nicht leer (enthalten mindestens
			 * eine Zeile)
			 */
			return fieldsIterator.hasNext() || lineIterator.hasNext();
		}

		@Override
		public Line next() {
			if (!lineIterator.hasNext()){
				/*
				 * Ist möglich, da hasNext() garantiert, dass
				 * da mindestens noch ein Feld in fields vorhanden ist:
				 */
				lineIterator = fieldsIterator.next().iterator();
			}
			return lineIterator.next();
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}

	}

	@Override
	public Iterator<Line> iterator() {
		// TODO Auto-generated method stub
		return new MyIterator();
	}
	
	@Override
	public String toString() {
		String s = "IDN: "+id;
		for (Line line : this) {
			s += "\n" + line;
		}
		return s;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
